import Vue from 'vue'
import VueRouter from 'vue-router'
import auth from '@/utils/token'
import { Message } from 'element-ui'
// import LoginPage from '@/views/login/index.vue'
// import Layout from '@/views/layout.vue'
// import Home from '@/views/home/index.vue'
// import Article from '@/views/article/index.vue'
// import Publish from '@/views/publish/index.vue'
// 按需加载路由组件
const LoginPage = () => import('@/views/login/index.vue')
const Layout = () => import('@/views/layout.vue')
const Home = () => import('@/views/home/index.vue')
const Article = () => import('@/views/article/index.vue')
const Publish = () => import('@/views/publish/index.vue')
// 注册全局路由组件
Vue.use(VueRouter)
const router = new VueRouter({
  // 配置路由表
  routes: [
    { path: '/login', component: LoginPage },
    {
      path: '/',
      component: Layout,
      // 注册子路由
      children: [
        { path: '', component: Home },
        { path: 'article', component: Article },
        { path: 'publish/:id?', component: Publish }
      ]
    }
  ]
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // to: 即将要进入的目标 路由对象 去哪里
  // from: 当前导航正要离开的路由 从哪来
  // next: 放行函数 默认加。若没有则白屏
  const token = auth.getToken()
  // 如果用户访问的不是登录页面且没有token，则跳转到登录页面
  if (to.path !== '/login' && !token) {
    // 非vue组件，需要单独导入Message实现提示
    Message.error('登录信息失效，请重新登录')
    return next('/login')
  }
  next()
})
// 导出路由实例
export default router
